/**
 * 原app.ux的公共方法
 * modify by 24-10-23
 */
const ad = require('@service.ad') // 使用require方式避免在不支持广告接口的厂商运行时报错
import storage from '@system.storage'
import device from '@system.device'
import { vendorIds } from '../helper/config.js'
import CryptoJs from 'crypto-js'
import { getGlobalData, setGlobalData } from '../global.js'

// 广告状态
function checkAdStatus() {
  return new Promise(async (resolve, reject) => {
    // 手机型号
    let adProvider = ad.getProvider()
    if (adProvider !== '') {
      adProvider = adProvider.toLowerCase()
      let vendorForm
      if (adProvider == 'vivo') vendorForm = vendorIds.vivo
      else if (adProvider == 'oppo') vendorForm = vendorIds.oppo
      else if (adProvider == 'xiaomi') vendorForm = vendorIds.xiaomi
      else if (adProvider == 'huawei') vendorForm = vendorIds.huawei
      console.log('adProvider:', adProvider, vendorForm)
      setGlobalData('adProvider', adProvider)
      setGlobalData('vendorForm', vendorForm)
    } else {
      console.error('广告提供商为空', adProvider)
      reject('广告提供商为空')
      return false
    }
    try {
      const idInfo = getGlobalData('idInfo') ? getGlobalData('idInfo') : await getId()
      const deviceInfo = getGlobalData('deviceInfo') ? getGlobalData('deviceInfo') : await getDeviceInfo()
      const oaid = getGlobalData('oaid') ? getGlobalData('oaid') : await getOaid()
      console.log('1-deviceInfo:', deviceInfo, '\n2-idInfo:', idInfo, '\n3-oaid', oaid)
      // 用户归因与广告配置
      const adconfig = await getAcquire()
    } catch (err) {
      console.error(err)
      reject(err)
    }
    console.log('1-adchannel:', getGlobalData('adchannel'), '\n2-adconfig:', getGlobalData('adconfig'))
    //激活列表
    // getActiveJson(adconfig ?.quickAppConfig ?.activeJson)
    //次留
    timeRemaining()
    /**
     * "channelSwitchStatus": 1,//渠道审核状态 0:未审核 1:已审核
     * "hasTagApp": 0,// 带标签应用内开关  1:开，非1：关
     * "noTagApp": 0,// 无标签应用内开关  1:开，非1：关
     */
    const { channelSwitchStatus, hasTagApp, noTagApp } = adconfig.channelSwitch
    if (channelSwitchStatus === 0) {
      console.error('广告配置未开启', channelSwitchStatus)
      reject('广告配置未开启')
      return false
    } else {
      console.error(`无标签开关:${noTagApp}｜带标签开关:${hasTagApp}`)
      if (noTagApp == 0) {
        if (hasTagApp == 0) {
          reject()
        } else {
          resolve('hasTagApp')
        }
      } else {
        resolve('noTagApp')
      }
    }
  })
}
// 用户归因与广告配置
function getAcquire() {
  return new Promise((resolve, reject) => {
    $apis.api
      .getAcquire()
      .then(res => {
        if (res.code == 200) {
          const data = res.data
          setGlobalData('adchannel', data)
          if (data.adLoadStr) {
            const word = data.adLoadStr
            let key = CryptoJs.enc.Utf8.parse('Z2U0VJoLEAMVi1xoPWyDaQ==00000000')
            let decrypt = CryptoJs.AES.decrypt(word, key, {
              mode: CryptoJs.mode.ECB,
              padding: CryptoJs.pad.Pkcs7
            })
            let decryptedData = JSON.parse(CryptoJs.enc.Utf8.stringify(decrypt).toString())
            setGlobalData('adconfig', decryptedData)
          }
          resolve()
        } else {
          reject('getAcquire failed')
        }
      })
      .catch(err => {
        reject('getAcquire status failed:', err)
      })
  })
}
// 激活列表
function getActiveJson(activeJsonUrl) {
  if (getGlobalData('activeJson')) return
  if (!activeJsonUrl) {
    console.error('activeJsonUrl is null')
    return false
  }
  return new Promise((resolve, reject) => {
    $apis.api
      .getActiveJson(activeJsonUrl)
      .then(res => {
        const list = Object.entries(res).reduce((pre, [, v]) => {
          return [...pre, v]
        }, [])
        setGlobalData('activeApkList', list)
        setGlobalData('activeJson', res)
        resolve(res)
      })
      .catch(() => {
        console.error('getActiveJson status failed')
      })
  })
}
// 纪录时间
async function setStorageTime(key, value) {
  // 次留只记首次时间
  if (key == 'clTime') {
    try {
      const data = await getStorageTime(key)
      if (data != '') {
        return
      }
    } catch (code) {
      console.error('getStorageTime fail', code)
    }
  }
  storage.set({
    key: key,
    value: value
  })
}
function getStorageTime(key) {
  return new Promise((resolve, reject) => {
    storage.get({
      key: key,
      success: data => {
        resolve(data)
      },
      fail: (data, code) => {
        reject(code)
      }
    })
  })
}
//次留
function timeRemaining() {
  if (getGlobalData('mutual') == 1) return //被动拉起不用上报
  storage.get({
    key: 'clTime',
    success: data => {
      if (!data) {
      } else {
        if (data == -1) return
        let now = new Date().getDate()
        let time = new Date(Number(data)).getDate()
        if (now > time) {
          const params = {
            event: '1005'
          }
          $apis.api.gethlAdLog(params).then(res => {
            // console.log('gethlAdLog',res)
            if (res.code == 200) {
              storage.set({
                key: 'clTime',
                value: -1
              })
            }
          })
        }
      }
    }
  })
}
function clearKeyBehaviors() {
  const deleteKeyBehaviors = new Promise(resolve => {
    storage.delete({
      key: 'keyBehaviors',
      success: data => {
        resolve(true)
      }
    })
  })
  const deleteTtArpu = new Promise(resolve => {
    storage.delete({
      key: 'ttArpu',
      success: data => {
        resolve(true)
      }
    })
  })
  return Promise.all([deleteKeyBehaviors, deleteTtArpu])
}
//关键行为+头条arpu门槛
function keyBehaviors(type, { price }) {
  if (getGlobalData('mutual') == 1) return //被动拉起不用上报
  // console.log('--keyBehaviors/ttArpu :type',type,'price:',price)
  const promise1 = new Promise((resolve, reject) => {
    storage.get({
      key: 'keyBehaviors',
      success: data => {
        resolve(data)
      }
    })
  })
  const promise2 = new Promise((resolve, reject) => {
    storage.get({
      key: 'ttArpu',
      success: data => {
        resolve(data)
      }
    })
  })
  const promise3 = new Promise((resolve, reject) => {
    storage.get({
      key: 'createTime',
      success: data => {
        if (!data) {
        } else {
          let now = Number(new Date())
          const timeDiff = $utils.calculateMinutes(now, data)
          resolve(timeDiff)
        }
      }
    })
  })
  Promise.all([promise1, promise2, promise3])
    .then(results => {
      let resultBid = results[2]
      // const appConfig = getGlobalData('adconfig').appConfig;
      this.setkeyBehaviors(type, price, results)
      this.setttArpu(type, price, results)
    })
    .catch(error => {
      console.error(error) // 输出 "Error occurred"
    })
}
function setkeyBehaviors(type, price, results) {
  let resultBid = results[2]
  const appConfig = getGlobalData('adconfig').appConfig
  // 关键行为
  if (appConfig.keyBehaviors) {
    let resultKey = results[0]
      ? JSON.parse(results[0])
      : {
          sumPrice: 0,
          frequency: 0,
          isLoadEcpm: false,
          kppricenew: 0,
          cppricenew: 0,
          qppricenew: 0,
          kppricenew1: 0,
          cppricenew1: 0,
          qppricenew1: 0
        }
    const keyBehaviors = JSON.parse(appConfig.keyBehaviors)
    // console.log('keyBehaviors',keyBehaviors,!keyBehaviors)
    if (!keyBehaviors) return
    const configType = keyBehaviors.type
    const configSumPrice = Number(keyBehaviors.sumPrice)
    const configBid = Number(keyBehaviors.bid)
    const configFrequency = Number(keyBehaviors.frequency)

    //1,是否上报过
    if (resultKey.isLoadEcpm) {
      console.warn('--keyBehaviors :上报过')
      return
    }
    //2,是否超时
    if (resultBid > configBid) {
      console.warn('--keyBehaviors :超时', resultBid, configBid)
      return
    }
    //总价
    if (configType == '') {
      // console.log('--keyBehaviors sumPrice:',Number(price),Number(resultKey.sumPrice))
      resultKey.sumPrice = Number(price) + Number(resultKey.sumPrice)
      if (resultKey.sumPrice > configSumPrice) {
        // todo
        this.reportKeyBehaviors(resultKey)
        return
      }
      storage.set({
        key: 'keyBehaviors',
        value: resultKey
      })
      return
    }
    //3,获取价格满足纪录
    let pricenew
    if (type == 1) {
      let item = keyBehaviors.kppricenew
      if (item && item.split('-').length == 2) {
        pricenew = parseInt(item.split('-')[0])
      } else {
        pricenew = -1
      }
    } else if (type == 2) {
      let item = keyBehaviors.qppricenew
      if (item && item.split('-').length == 2) {
        pricenew = parseInt(item.split('-')[0])
      } else {
        pricenew = -1
      }
    } else if (type == 3) {
      let item = keyBehaviors.cppricenew
      if (item && item.split('-').length == 2) {
        pricenew = parseInt(item.split('-')[0])
      } else {
        pricenew = -1
      }
    } else {
      pricenew = -1
    }
    // 或、且
    if (configType == 0) {
      if (pricenew != -1 && price >= pricenew) {
        switch (type) {
          case 1:
            resultKey.kppricenew++
            break
          case 2:
            resultKey.qppricenew++
            break
          case 3:
            resultKey.cppricenew++
            break
        }
      }
      // console.log('--keyBehaviors :configType',configType,resultKey)
      if (resultKey.kppricenew + resultKey.qppricenew + resultKey.cppricenew >= configFrequency) {
        // todo
        this.reportKeyBehaviors(resultKey)
        return
      }
      storage.set({
        key: 'keyBehaviors',
        value: resultKey
      })
    } else if (configType == 1) {
      if (pricenew != -1 && price >= pricenew) {
        switch (type) {
          case 1:
            resultKey.kppricenew1++
            break
          case 2:
            resultKey.qppricenew1++
            break
          case 3:
            resultKey.cppricenew1++
            break
        }
      }
      let requestTimes = getGlobalData('requestTimes') || 0
      if (requestTimes >= configFrequency) {
        //计算各类型满足次数满足条件
        let isKpp
        let isCpp
        let isQpp
        let isKppItem = keyBehaviors.kppricenew
        if (isKppItem && isKppItem.split('-').length == 2) {
          isKpp = resultKey.kppricenew1 >= parseInt(isKppItem.split('-')[1])
        } else {
          isKpp = true
        }
        let isCppItem = keyBehaviors.cppricenew
        if (isCppItem && isCppItem.split('-').length == 2) {
          isCpp = resultKey.cppricenew1 >= parseInt(isCppItem.split('-')[1])
        } else {
          isCpp = true
        }
        let isQppItem = keyBehaviors.qppricenew
        if (isQppItem && isQppItem.split('-').length == 2) {
          isQpp = resultKey.qppricenew1 >= parseInt(isQppItem.split('-')[1])
        } else {
          isQpp = true
        }
        // console.log('--keyBehaviors 且:',getGlobalData('requestTimes'),isKpp,isCpp,isQpp)
        if (isKpp && isCpp && isQpp) {
          //todo
          this.reportKeyBehaviors(resultKey)
          return
        }
      }
      storage.set({
        key: 'keyBehaviors',
        value: resultKey
      })
    }
  }
}
function setttArpu(type, price, results) {
  let resultBid = results[2]
  const appConfig = getGlobalData('adconfig').appConfig
  // 头条
  if (appConfig.ttArpu) {
    let resultKey = results[1]
      ? JSON.parse(results[1])
      : {
          sumPrice: 0,
          frequency: 0,
          isLoadEcpm: false,
          kppricenew: 0,
          cppricenew: 0,
          qppricenew: 0,
          kppricenew1: 0,
          cppricenew1: 0,
          qppricenew1: 0
        }
    const ttArpu = JSON.parse(appConfig.ttArpu)
    // console.log('ttArpu',ttArpu,!ttArpu)
    if (!ttArpu) return
    const configType = ttArpu.type
    const configSumPrice = Number(ttArpu.sumPrice)
    const configBid = Number(ttArpu.bid)
    const configFrequency = Number(ttArpu.frequency)

    //1,是否上报过
    if (resultKey.isLoadEcpm) {
      console.warn('--ttArpu :上报过')
      return
    }
    //2,是否超时
    if (resultBid > configBid) {
      console.warn('--ttArpu :超时', resultBid, configBid)
      return
    }
    //总价
    if (configType == '') {
      // console.log('--ttArpu sumPrice:',Number(price),Number(resultKey.sumPrice))
      resultKey.sumPrice = Number(price) + Number(resultKey.sumPrice)
      if (resultKey.sumPrice > configSumPrice) {
        resultKey.isLoadEcpm = true
        // todo
        this.reportTTArpu(resultKey)
      }
      storage.set({
        key: 'ttArpu',
        value: resultKey
      })
      return
    }
    //3,获取价格满足纪录
    let pricenew
    if (type == 1) {
      let item = ttArpu.kppricenew
      if (item && item.split('-').length == 2) {
        pricenew = parseInt(item.split('-')[0])
      } else {
        pricenew = -1
      }
    } else if (type == 2) {
      let item = ttArpu.qppricenew
      if (item && item.split('-').length == 2) {
        pricenew = parseInt(item.split('-')[0])
      } else {
        pricenew = -1
      }
    } else if (type == 3) {
      let item = ttArpu.cppricenew
      if (item && item.split('-').length == 2) {
        pricenew = parseInt(item.split('-')[0])
      } else {
        pricenew = -1
      }
    } else {
      pricenew = -1
    }
    // 或、且
    if (configType == 0) {
      if (pricenew != -1 && price >= pricenew) {
        switch (type) {
          case 1:
            resultKey.kppricenew++
            break
          case 2:
            resultKey.qppricenew++
            break
          case 3:
            resultKey.cppricenew++
            break
        }
      }
      // console.log('--ttArpu :configType',configType,resultKey)
      if (resultKey.kppricenew + resultKey.qppricenew + resultKey.cppricenew >= configFrequency) {
        resultKey.isLoadEcpm = true
        this.reportTTArpu(resultKey)
      }
      storage.set({
        key: 'ttArpu',
        value: resultKey
      })
    } else if (configType == 1) {
      if (pricenew != -1 && price >= pricenew) {
        switch (type) {
          case 1:
            resultKey.kppricenew1++
            break
          case 2:
            resultKey.qppricenew1++
            break
          case 3:
            resultKey.cppricenew1++
            break
        }
      }
      let requestTimes = getGlobalData('requestTimes') || 0
      if (requestTimes >= configFrequency) {
        //计算各类型满足次数满足条件
        let isKpp
        let isCpp
        let isQpp
        let isKppItem = ttArpu.kppricenew
        if (isKppItem && isKppItem.split('-').length == 2) {
          isKpp = resultKey.kppricenew1 >= parseInt(isKppItem.split('-')[1])
        } else {
          isKpp = true
        }
        let isCppItem = ttArpu.cppricenew
        if (isCppItem && isCppItem.split('-').length == 2) {
          isCpp = resultKey.cppricenew1 >= parseInt(isCppItem.split('-')[1])
        } else {
          isCpp = true
        }
        let isQppItem = ttArpu.qppricenew
        if (isQppItem && isQppItem.split('-').length == 2) {
          isQpp = resultKey.qppricenew1 >= parseInt(isQppItem.split('-')[1])
        } else {
          isQpp = true
        }
        // console.log('--ttArpu 且:',getGlobalData('requestTimes'),isKpp,isCpp,isQpp)
        if (isKpp && isCpp && isQpp) {
          resultKey.isLoadEcpm = true
          //todo
          this.reportTTArpu(resultKey)
        }
      }
      storage.set({
        key: 'ttArpu',
        value: resultKey
      })
    }
  }
}
async function reportKeyBehaviors(item) {
  let resultKey = item
  const publicParams = getGlobalData('publicParams')
  const caid1 = publicParams?.caid1
  const ad_platform = publicParams?.ad_platform
  const channel = publicParams?.channel
  const adchannel = getGlobalData('adchannel')
  const isOtherTotalSwitch = adchannel?.isOtherTotalSwitch //是否正常标签匹配
  if (channel == 'vivo' && ad_platform == 7 && caid1 && isOtherTotalSwitch) {
    resultKey.isLoadEcpm = false
    try {
      let checkReport = await $apis.api.getCheckReport({
        caid1,
        adPlatform: ad_platform,
        channel,
        event: '1000'
      })
      if (checkReport.code == 200 && checkReport.data?.isNeedReport) {
        //判定是否由热云上报
        resultKey.isLoadEcpm = true
        const idInfo = getGlobalData('idInfo')
        const accountId = idInfo?.device || idInfo?.user || 'default_account'
        // $utils.showToast('vivo关键上报为激活caid1'+caid1+'|accountId:'+accountId)
        console.log('vivo关键上报为激活caid1:' + caid1 + '|accountId:' + accountId)
        if (caid1 == 'gj') {
          TrackingIO.event('event_1', accountId)
        }
        if (caid1 == 'gjjz') {
          TrackingIO.event('event_2', accountId)
        }
      }
    } catch (err) {
      console.log('getCheckReport catch:', err)
    }
    storage.set({
      key: 'keyBehaviors',
      value: resultKey
    })
  } else {
    resultKey.isLoadEcpm = true
    storage.set({
      key: 'keyBehaviors',
      value: resultKey
    })
    const params = {
      event: '1000'
    }
    $apis.api.gethlAdLog(params).then(res => {
      if (res.code == 200) {
      }
    })
  }
}
function reportTTArpu() {
  const params = {
    event: '1004'
  }
  $apis.api.gethlAdLog(params).then(res => {
    if (res.code == 200) {
    }
  })
}
//请求次数达到要求后上报
function jhsbyqpz() {
  if (getGlobalData('mutual') == 1) return //被动拉起不用上报
  storage.get({
    key: 'requestTimes',
    success: data => {
      let requestTimes = !data ? { times: 0, isLoadTimes: false } : JSON.parse(data)
      // console.log('读取requestTimes',requestTimes)
      requestTimes.times = Number(requestTimes.times) + 1
      setGlobalData('requestTimes', requestTimes.times)
      storage.set({
        key: 'requestTimes',
        value: requestTimes
      })
      if (requestTimes.isLoadTimes) return
      const appConfig = getGlobalData('adconfig').appConfig
      const jhsbyqpz = Number(appConfig.jhsbyqpz)
      if (jhsbyqpz && requestTimes.times >= jhsbyqpz) {
        requestTimes.isLoadTimes = true
        const params = {
          event: '1006'
        }
        $apis.api.gethlAdLog(params).then(res => {
          if (res.code == 200) {
            storage.set({
              key: 'requestTimes',
              value: requestTimes
            })
          }
        })
      }
    }
  })
}

// 获取设备信息
function getDeviceInfo() {
  return new Promise((resolve, reject) => {
    // 优先从存储中获取
    let deviceInfo = getGlobalData('deviceInfo')
    // 如果存储中已有 直接返回
    if (deviceInfo) {
      resolve(deviceInfo)
      return
    }
    // 如果存储中没有 从接口获取
    device.getInfo({
      success: data => {
        let brand = data.brand.toLowerCase()
        let model = data.model.toLowerCase()
        let deviceInfo = { ...data, brand: brand, model: model }
        setGlobalData('deviceInfo', deviceInfo)
        resolve(deviceInfo)
      },
      fail: (data, code) => {
        console.error(`getInfo fail ### ${code}: ${data}`)
        reject(false)
      }
    })
  })
}
// 获取设备ID
function getId() {
  return new Promise((resolve, reject) => {
    // 优先从存储中获取
    let idInfo = getGlobalData('idInfo')
    // 如果存储中已有 直接返回
    if (idInfo) {
      resolve(idInfo)
      return
    }
    // 如果存储中没有 从接口获取
    device.getId({
      type: ['device', 'mac', 'user', 'advertising'],
      success: data => {
        const { device, mac, user, advertising } = data
        setGlobalData('idInfo', data)
        setGlobalData('androidId', user)
        resolve(data)
      },
      fail: (data, code) => {
        console.error(`getId fail ### ${code}: ${data}`)
        reject(false)
      }
    })
  })
}
// 获取设备标识
function getOaid() {
  return new Promise((resolve, reject) => {
    // 优先从存储中获取
    let oaid = getGlobalData('oaid')
    // 如果存储中已有 直接返回
    if (oaid) {
      resolve(oaid)
      return
    }
    // 如果存储中没有 从接口获取
    device.getOAID({
      success: data => {
        setGlobalData('oaid', data)
        resolve(data)
      },
      fail: (data, code) => {
        console.error(`getOaid fail ### ${code}: ${data}`)
        reject(false)
      }
    })
  })
}
// 获取注册时间
function getRegisterTime() {
  return new Promise((resolve, reject) => {
    // 优先从存储中获取
    let registerTime = getGlobalData('registerTime')
    // 如果存储中已有 直接返回
    if (registerTime) {
      resolve(registerTime)
      return
    }
    const key = 'registerTime'
    const time = $utils.getFormattedDate()
    storage.get({
      key,
      success: data => {
        if (data != '') {
          setGlobalData('registerTime', data)
          resolve(data)
        } else {
          storage.set({
            key,
            value: time
          })
          setGlobalData('registerTime', time)
          resolve(time)
        }
      },
      fail: (data, code) => {
        storage.set({
          key,
          value: time
        })
        setGlobalData('registerTime', time)
        resolve(time)
      }
    })
  })
}
export default {
  clearKeyBehaviors,
  checkAdStatus,
  getActiveJson,
  setStorageTime,
  timeRemaining,
  keyBehaviors,
  setkeyBehaviors,
  setttArpu,
  reportKeyBehaviors,
  reportTTArpu,
  jhsbyqpz,
  getDeviceInfo,
  getId,
  getOaid,
  getRegisterTime
}
